package com.qf.bookks.filter;

import com.qf.bookks.utils.Constants;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 注销过滤器
 */

@Slf4j
public class LogoutFilter implements Filter {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("过滤器被初始化了");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 强制转成 HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;


        // 1. 清空session中的 用户登录信息
        final HttpSession session = req.getSession();
        session.setAttribute(Constants.USER_LOGIN_SESSION_KEY,null);

        // 2. 把用户浏览器本地的 cookie 删除掉
        final Cookie cookie = new Cookie(Constants.AUTOLOGIN_COOKIE_KEY, "delete-user-token");
        cookie.setPath("/");
        cookie.setMaxAge(0); // 把cookie的有效期设置为0，会让浏览器马上删除该cookie

        resp.addCookie(cookie);

        // 请求就此打住,重定向到 /login.html
        resp.sendRedirect("/login.html");

    }

    @Override
    public void destroy() {
        log.debug("过滤器被销毁了");
    }
}
